package com.example.config;

import com.example.filter.JwtAuthenticationEntryPoint;
import com.example.filter.JwtAuthenticationFilter;
import com.example.filter.UserLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author 王鹤蒲
 * @Date 2023 09 15
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;




    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    private static final String[] urls={"/test/**","/druid/**","/user/getCaptcha","/user/login","/user/register","/file/*","/swagger-ui/**","/swagger-resources/**","/v3/**", "/error","/user/getCaptcha","/user/sendEmailCode","/user/verifyEmailCode","/user/isPhonenumberExist","/user/isUsernameExist","/user/isEmailExist","/user/verifyUserEmail","/user/updatePassword"};

    @Override
    public void configure(WebSecurity webSecurity){
        webSecurity.ignoring().antMatchers(urls);
    }



    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers(urls).permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and()
                .addFilter(new JwtAuthenticationFilter(authenticationManagerBean()))
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new UserLogoutSuccessHandler());
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}
